package gui.windows.components;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JList;

import cardmanager.CardInfo;
import cardmanager.CardManager;

@SuppressWarnings("serial")
public class CardList extends JList<CardInfo> {
	DefaultListModel<CardInfo> modelList;
	public CardList(){
		modelList = new DefaultListModel<CardInfo>();
		this.setModel(modelList);
		this.setCellRenderer(new CardCellRenderer());
	}
	public void loadDeck(File deck){
		clearCards();
	    BufferedReader file = null;
	    try {
	    	file = new BufferedReader(new FileReader(deck));
	    
	        ArrayList<String> cardids = new ArrayList<String>();
	        String line = file.readLine();

	        while (line != null) {
	        	cardids.add(line);
	            line = file.readLine();
	        }
	        for(String id: cardids){
	        	if(id.startsWith("#") || id.startsWith("!"))
	        		continue;
	        	CardInfo card = CardManager.fromId(Integer.parseInt(id));
	        	if(card != null)
	        		addCard(card);
	        }
	        
	    } catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(file != null){
				try {
					file.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	    }
	}
	public void addCard(CardInfo card){
        for (int i = 0; i < modelList.getSize(); i++) {
            CardInfo item = modelList.getElementAt(i);
            if(item.getName() == card.getName()){
            	item.count++;
            	return;
            }
        }	
		try {
			modelList.addElement(card.clone());
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void addCards(CardInfo[] cards){
		for(CardInfo card: cards){
			addCard(card);
		}
	}
	public void clearCards(){
		modelList.clear();
	}

}
